'use strict';

let nunjucks = require('nunjucks');

function createEnvInstance(path, opts) {
    path = path || 'views';
    opts = opts || {};

    let envOption = {
        autoescape: opts.autoescape === undefined ? true : opts.autoescape,

        throwOnUndefined: opts.throwOnUndefined === undefined ? false : opts.throwOnUndefined,

        watch: opts.watch === undefined ? true : opts.watch,
        noCache: opts.noCache === undefined ? true : opts.noCache
    };

    let env = nunjucks.configure(path, envOption);

    return env;
};

module.exports = async (ctx, next) => {
    ctx.render = function (view, model) {
        let env = createEnvInstance();

        ctx.body = env.render(view, model);
    };

    await next();
};